# 导入所需库
import cv2
from skimage.segmentation import kmeans_clustering

# 读取图像
img = cv2.imread('your_image_path.jpg')

# 转换为RGB
rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# K-means参数设置，例如选择k=3（假设想要3种主要的颜色）
n_clusters = 3
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
flags = cv2.KMEANS_RANDOM_CENTERS

# 进行聚类
colors, labels, centers = kmeans_clustering(rgb_img.reshape(-1, 3), n_clusters, criteria, flags, attempts=10)

# 根据聚类标签重新组织图像
segmented_img = labels.reshape(img.shape[:-1])

# 显示原图和分割后的图像
cv2.imshow('Original Image', img)
cv2.imshow('Segmented Image', segmented_img)
cv2.waitKey(0)
cv2.destroyAllWindows()